﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
public partial class Main_Inventory_AdminPurchaseOrderApproval : System.Web.UI.Page
{
    //For the Global Variable and the Method.
    #region
    Datautility DU = new Datautility();
    DataTable dttotal = new DataTable();
    Label Body = new Label();
    //Pageid=1026;
    int TotalQty = 0;
    double TotalValue = 0;
    #endregion
    //for the Page load 
    #region
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["userid"] == null)
        {
            if (Request.QueryString["redirect"] != null)
            {
                if (Request.QueryString["redirect"].ToString() == "PA")
                {
                    Response.Redirect("~/SessionExpired.aspx?redirect=PA");
                }
            }
            else
            {
                Response.Redirect("~/SessionExpired.aspx");
            }
        }
        else
        {
            //For Checking the Permission of the Page according to the User.
            string Pagepermission = "select PAGE_ID,PAGE_EDIT,PAGE_VIEW,USERID,USERNAME as EmailID from USER_PERMISSION inner join LOGIN on USER_PERMISSION.USER_ID=LOGIN.USERID where USER_ID='" + Session["userid"].ToString() + "' and PAGE_ID=1026";
            DataTable dt = DU.getdata(Pagepermission);
            if (dt.Rows.Count > 0)
            {
                if (Request.QueryString["mode"] == "edit")
                {
                    if (dt.Rows[0]["PAGE_EDIT"].ToString() == "True")
                    {
                        PanelDisplay.Visible = false;
                        //paneledit.Visible = true;
                        pnlview.Visible = true;
                        grdviewpnl.Visible = true;
                        string po_id = Request.QueryString["key"].ToString();
                        if (!IsPostBack)
                        {
                            bindEditFields(po_id);
                            BindviewGrd(po_id);
                            BindItem(po_id);
                            BindTotal(po_id);
                            binddetail(po_id);
                            hidemailId.Value = dt.Rows[0]["EmailID"].ToString();
                        }
                    }
                    else
                    {
                        Response.Redirect("~/AccessDenied.aspx");
                    }
                }
                if (Request.QueryString["View"] == "True")
                {
                    if (dt.Rows[0]["PAGE_VIEW"].ToString() == "True")
                    {
                        PanelDisplay.Visible = true;
                        //paneledit.Visible = false;
                        grdviewpnl.Visible = false;
                        pnlview.Visible = false;
                        bindgrid();
                    }
                    else
                    {
                        Response.Redirect("~/AccessDenied.aspx");
                    }
                }
            }            
        }
    }
    protected void bindgrid() //on Page load
    {
        //string sql1 = "select * from ACC_POMAIN";
        string sql1 = "select * from ACC_POMAIN where [Status] in(5,8,9,10) order by ApprovalDate desc";
        DataTable DT = DU.getdata(sql1);
        DataTable Display = new DataTable();
        if (DT.Rows.Count > 0)
        {
            Display.Columns.Add("POID", typeof(System.String));
            Display.Columns.Add("PONo", typeof(System.String));
            Display.Columns.Add("cdate", typeof(System.String));
            //Display.Columns.Add("edate", typeof(System.String));
            Display.Columns.Add("PODate", typeof(System.String));
            Display.Columns.Add("cname", typeof(System.String));
            Display.Columns.Add("ename", typeof(System.String));
            //Display.Columns.Add("ApprovalBy", typeof(System.String));
            Display.Columns.Add("Status", typeof(System.String));
            Display.Columns.Add("ApprovalDate", typeof(System.String));
            for (int i = 0; i < DT.Rows.Count; i++)
            {
                string vouchermain = "";
                string prefix = "";
                string vono = "";
                string suffix = "";

                DataRow DRow = Display.NewRow();
                // DRow["ID"] = DT.Rows[i]["ID"];
                DRow["POID"] = DT.Rows[i]["POID"];

                if (DT.Rows[i]["PoPrefix"].ToString() != string.Empty)
                {
                    prefix = DT.Rows[i]["PoPrefix"].ToString() + "/";
                }
                if (DT.Rows[i]["PoVoucherNo"].ToString() != string.Empty)
                {
                    vono = DT.Rows[i]["PoVoucherNo"].ToString();
                }
                if (DT.Rows[i]["PoSuffix"].ToString() != string.Empty)
                {
                    suffix = "/" + DT.Rows[i]["PoSuffix"].ToString();
                }
                vouchermain = prefix + vono + suffix;
                DRow["PONo"] = vouchermain;
                DRow["cdate"] = string.Format("{0:dd-MMM-yyyy}", Convert.ToDateTime(DT.Rows[i]["PODate"].ToString()));
                DateTime po_date = Convert.ToDateTime(DT.Rows[i]["PODate"].ToString());
                DRow["PODate"] = string.Format("{0:dd-MMM-yyyy}", po_date);
                DRow["cname"] = DT.Rows[i]["cname"];
                DRow["ename"] = DT.Rows[i]["ename"];
                if (DT.Rows[i]["ApprovalDate"].ToString() != string.Empty)
                {
                    DRow["ApprovalDate"] = string.Format("{0:dd-MMM-yyyy}", Convert.ToDateTime(DT.Rows[i]["ApprovalDate"].ToString()));
                }
                if (DT.Rows[i]["Status"].ToString().Equals("3"))
                {
                    DRow["Status"] = "Sent To Finance.";
                }
                if (DT.Rows[i]["Status"].ToString().Equals("4"))
                {
                    DRow["Status"] = "Sent For Revision By Manager";
                }
                if (DT.Rows[i]["Status"].ToString().Equals("5"))
                {
                    DRow["Status"] = "Pending For Admin Approval";
                }
                if (DT.Rows[i]["Status"].ToString().Equals("6"))
                {
                    DRow["Status"] = "Sent For Revision By Finance";
                }
                if (DT.Rows[i]["Status"].ToString().Equals("7"))
                {
                    DRow["Status"] = "Reject By Finance.";
                }
                if (DT.Rows[i]["Status"].ToString().Equals("8"))
                {
                    DRow["Status"] = "Approved By Admin";
                }
                if (DT.Rows[i]["Status"].ToString().Equals("9"))
                {
                    DRow["Status"] = "Sent For Revision By Admin.";
                }
                if (DT.Rows[i]["Status"].ToString().Equals("10"))
                {
                    DRow["Status"] = "Reject By Admin.";
                }
                Display.Rows.Add(DRow);
            }
            grdDisplay.DataSource = Display;
            grdDisplay.DataBind();
        }
    }
    #endregion
    //For the Method and Function
    #region
    private void BindviewGrd(string po_id)
    {
        string sql_select = "select ACC_POMAIN.POID, CONVERT(smalldatetime,podate)as PODATE,Mas_Currency.currency_name as Currency ,priority, case Cash_Credit when 0 then 'Advance' when 2 then 'Cash on Delivery'when 3 then 'Free Of Cost' when 1 then 'Credit on Days' End As Cash_Credit ,case LEASEDTYPE when 1 then 'Owned' when 2 then 'Consigned' end as LeasedType, IVR_WAREHOUSE.WHSLOCATION as DELIVERYLOC,ACC_LEDMAST.LNAME as Supplier, LEASEDTYPE,IVR_TRANFORMAT.FORMATNAME from ACC_POMAIN inner join IVR_WAREHOUSE ON ACC_POMAIN.DeliveryLocation=IVR_WAREHOUSE.WHSID inner join Mas_Currency on ACC_POMAIN.currency=Mas_Currency.id inner join ACC_LEDMAST on ACC_POMAIN.LID=ACC_LEDMAST.LID inner join IVR_TRANFORMAT on IVR_TRANFORMAT.TFOID=ACC_POMAIN.BillFormatID where ACC_POMAIN.POID=" + po_id;
        DataTable DT = DU.getdata(sql_select);
        if (DT.Rows.Count > 0)
        {
            //grdviewpnl.DataSource = DT;
            //grdviewpnl.DataBind();
            lbldate.Text = Convert.ToDateTime(DT.Rows[0]["PODATE"]).ToString(string.Format("dd/MM/yyyy"));
            lblsupplier.Text = DT.Rows[0]["SUPPLIER"].ToString();
            lbllocation.Text = DT.Rows[0]["DELIVERYLOC"].ToString();
            lblpriority.Text = DT.Rows[0]["priority"].ToString();
            lblleagetype.Text = DT.Rows[0]["LeasedType"].ToString();
            lblpaymentmode.Text = DT.Rows[0]["Cash_Credit"].ToString();
            lblCurrency.Text = DT.Rows[0]["Currency"].ToString();
            lblBillFormat.Text = DT.Rows[0]["FORMATNAME"].ToString();
        }
    }
    private void BindItem(string poid)
    {
        string sql_item = "select IVR_ITEM.ITMDESC+'/'+IVR_ITEM.ITMCODE as ItemName,UOMSYMBOL as Unit,ISNULL(MPNNO,'')as MPNNO,ITEMQTY, RATEINCLTAX,TAXTYPE,RATEEXCLTAX,TOTALAMOUNT from ACC_PODETAILS inner join IVR_UOM on IVR_UOM.UOMID=ACC_PODETAILS.UOMID inner join IVR_ITEM on IVR_ITEM.ITMID=ACC_PODETAILS.ITEMID where ACC_PODETAILS.POID=" + poid;
        DataTable dtitem = DU.getdata(sql_item);
        if (dtitem.Rows.Count > 0)
        {
            grditem.DataSource = dtitem;
            grditem.DataBind();
        }
    }
    private void BindTotal(string poid)
    {
        string sql_total = "select totalqty,taxableamt,taxamt,posttaxtotal,grandtotal from ACC_POMAIN where poid=" + poid;
        dttotal = DU.getdata(sql_total);
        if (dttotal.Rows.Count > 0)
        {
            grdtotal.DataSource = dttotal;
            grdtotal.DataBind();
            if (dttotal.Rows.Count > 0)
            {
                hidtotalQty.Value = dttotal.Rows[0]["totalqty"].ToString();
                hidtaxtotal.Value = dttotal.Rows[0]["taxableamt"].ToString();
            }
        }
    }
    private void binddetail(string poid)
    {
        string sqldetail = "select * from ACC_POMAIN where POID=" + poid;
        DataTable DT = DU.getdata(sqldetail);
        if (DT.Rows.Count > 0)
        {
            txtBillAddress.Text = DT.Rows[0]["BillingAddress"].ToString();
            txtDeliveryAdd.Text = DT.Rows[0]["DeliveryAddress"].ToString();
            txtDeliveryTerms.Text = DT.Rows[0]["DeliveryTerms"].ToString();
            txtDeliveryMode.Text = DT.Rows[0]["DeliveryMode"].ToString();
            if (DT.Rows[0]["DeliveryDate"].ToString() != "")
            {
                txtDeliveryDate.Text = Convert.ToDateTime(DT.Rows[0]["DeliveryDate"]).ToString(string.Format("dd/MM/yyyy"));
            }
            txtOtheremarks.Text = DT.Rows[0]["Remarks"].ToString();
            lblfreightForwaders.Text = DT.Rows[0]["FreightFWD"].ToString();
            lblImportAcNo.Text = DT.Rows[0]["ImportAC_No"].ToString();
            lblacceptancecriteris.Text = DT.Rows[0]["AcceptanceCriteria"].ToString();
            lblvalidityofPO.Text = DT.Rows[0]["ValidityOfPO"].ToString();
            lblinsurance.Text = DT.Rows[0]["Insurance"].ToString();
            lblwarranty.Text = DT.Rows[0]["Warranty"].ToString();
            lblanyspecialcondition.Text = DT.Rows[0]["AnySpecialCondition"].ToString();
        }
    }
    private void bindEditFields(string po_id)
    {
        string sql_select = "select POID,PoPrefix,PoSuffix,PoVoucherNo,status,cname from ACC_POMAIN where POID=" + po_id;
        DataTable DT = DU.getdata(sql_select);
        if (DT.Rows.Count > 0)
        {
            string vouchermain = "";
            string prefix = "";
            string vono = "";
            string suffix = "";

            if (DT.Rows[0]["PoPrefix"].ToString() != string.Empty)
            {
                prefix = DT.Rows[0]["PoPrefix"].ToString() + "/";
            }
            if (DT.Rows[0]["PoVoucherNo"].ToString() != string.Empty)
            {
                vono = DT.Rows[0]["PoVoucherNo"].ToString();
            }
            if (DT.Rows[0]["PoSuffix"].ToString() != string.Empty)
            {
                suffix = "/" + DT.Rows[0]["PoSuffix"].ToString();
            }
            vouchermain = prefix + vono + suffix;
            lblpurchaseorder.Text = vouchermain;
            // lblpurchaseorder.Text = DT.Rows[0]["POID"].ToString();
            //DdlStatus.SelectedValue = DT.Rows[0]["Status"].ToString();
            lblorderplace.Text = DT.Rows[0]["cname"].ToString();
        }
    }
    private string IpAddress()
    {
        string strIpAddress;
        strIpAddress = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];

        if (strIpAddress == null)
        {
            strIpAddress = Request.ServerVariables["REMOTE_ADDR"];
        }
        return strIpAddress;

    }
    #endregion
    //For the Sending Mail
    #region
    protected void MailBody()
    {
        this.Controls.Add(Body);
        for (int i = 0; i < grditem.Rows.Count; i++)
        {
            Label lblItemName = (Label)grditem.Rows[i].FindControl("lblItemName");
            Label lblUnit = (Label)grditem.Rows[i].FindControl("lblUnit");
            Label lblMPNNO = (Label)grditem.Rows[i].FindControl("lblMPNNO");
            Label lblqty = (Label)grditem.Rows[i].FindControl("lblqty");
            Label lblrateexcltax = (Label)grditem.Rows[i].FindControl("lblrateexcltax");
            Label lbltotalamount = (Label)grditem.Rows[i].FindControl("lbltotalamount");
            //string abc = lblItemName.Text + "" + lblUnit.Text + "" + lblqty.Text + "" + lblrateexcltax.Text + "" + lbltotalamount.Text;
            //MailTextBody(itemdetail[0], itemdetail[1], txtUnit.Text, Convert.ToDecimal(txtQty.Text).ToString(), Convert.ToDecimal(txtRateExcTax.Text).ToString(), Convert.ToDecimal(taxableAmt).ToString("N2"));
            //MailTextBody(dtitem.Rows[i]["ItemName"].ToString(), dtitem.Rows[i]["ItemCODE"].ToString(), dtitem.Rows[i]["Unit"].ToString(), dtitem.Rows[i]["ITEMQTY"].ToString(), dtitem.Rows[i]["RateExclTax"].ToString(), dtitem.Rows[i]["TotalAmount"].ToString());
            Body.Text += "<tr><td style='border:1px solid #818181;'>" + lblItemName.Text + "</td><td style='border:1px solid #818181;'>" + lblUnit.Text + "</td><td style='border:1px solid #818181; text-align:right;'>" + lblqty.Text + "</td><td style='border:1px solid #818181; text-align:right;'>" + lblrateexcltax.Text + "</td><td style='border:1px solid #818181; text-align:right;'>" + lbltotalamount.Text + "</td></tr>";
        }
    }
    protected void SendEMail(string StatusCheck)
    {
        try
        {
            DataTable DtMail = DU.getdata("Select * from Acc_EmailSetting");
            if (DtMail.Rows.Count > 0)
            {
                System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage();
                mail.To.Add("vishnuchit.vats@ctdi.in,dshukla@ctdi.com");
                mail.Bcc.Add("harish@digitalsolutions.co.in");
                mail.From = new System.Net.Mail.MailAddress(hidemailId.Value, DtMail.Rows[1]["MailDisplayName"].ToString().Trim());
                mail.Subject = "Dis-Account";
                mail.IsBodyHtml = true;
                //mail.Body = "<table width='80%' cellpadding='0' cellspacing='0' style='font-family: Arial, Helvetica, sans-serif; font-size: small; font-weight: normal'><tr><td>Dear Sir/Madam</td></tr><tr><td>&nbsp;Following purchase order has been approved By Admin :-</td></tr><tr><td align='center'><table style='border: 1px solid #818181; width: 80%; font-family: Arial, Helvetica, sans-serif; font-size: small; font-weight: normal;' cellpadding='0' cellspacing='0'><tr style='background-color: #4D8732;'><td colspan='4' style='color: white; border: 1px solid #818181;' align='left'><b>Purchase Order Detail</b></td></tr><tr><td><b>PO No</b></td><td colspan='3' align='left'>"+lblpurchaseorder.Text+"</td></tr><tr><td><b>Bill Format</b></td><td>" + ddlFormat.SelectedItem.ToString() + "</td><td><b>Supplier</b></td><td>" + ddlSupplier.SelectedItem.ToString() + "</td></tr><tr><td><b>Leased Type</b></td><td>" + ddlleased.SelectedItem.ToString() + "</td><td><b>Delivery Location</b></td><td>" + DdlLocation.SelectedItem.ToString() + "</td></tr><tr><td><b>Currency</b></td><td>" + ddlcurrency.SelectedItem.ToString() + "</td><td></td></tr></table></td></tr><tr><td><table style='border: 1px solid #818181; width: 100%; font-family: Arial, Helvetica, sans-serif; font-size: small; font-weight: normal;' cellpadding='0' cellspacing='0'><tr style='background-color: #4D8732;'><td colspan='5' style='color: white; border: 1px solid #818181;'><b>Item Detail</b></td></tr><tr><td style='border: 1px solid #818181; width: 40%;'><b>Item Name / Item Code</b></td><td style='border: 1px solid #818181; width: 10%;'><b>UOM</b></td><td style='border: 1px solid #818181; width: 10%;'><b>Qty</b></td><td style='border: 1px solid #818181; width: 10%;'><b>Rate</b></td><td style='border: 1px solid #818181; width: 15%;'><b>Amount Payable</b></td></tr>" + Body + "</table></td></tr><tr><td align='right'><table style='border: 1px solid #818181; width: 40%; font-family: Arial, Helvetica, sans-serif; font-size: small; font-weight: normal;' cellpadding='0' cellspacing='0'><tr><td style='border: 1px solid #818181; width: 16%;'><b>Item Total</b></td><td style='border: 1px solid #818181; text-align: right; width: 14%;'>" + Convert.ToDecimal(txtTotalItem.Text) + "</td></tr><tr><td style='border: 1px solid #818181;'><b>Taxable Amount</b></td><td style='border: 1px solid #818181; text-align: right;'>" + Convert.ToDecimal(txtTaxableAmt.Text) + "</td></tr></table></td></tr><tr><td><b>Thanks & Regards</b></td></tr><tr><td><a href='http:\\103.13.97.96/demo/index.aspx' target='_blank'>Click here for login</a></td></tr></table>";
                mail.Body = "<table width='80%' cellpadding='0' cellspacing='0' style='font-family: Arial, Helvetica, sans-serif; font-size: small; font-weight: normal'><tr><td>Dear Sir/Madam</td></tr><tr><td>&nbsp;Following purchase order " + StatusCheck + " By Admin :-</td></tr><tr><td align='center'><table style='border: 1px solid #818181; width: 80%; font-family: Arial, Helvetica, sans-serif; font-size: small; font-weight: normal;' cellpadding='0' cellspacing='0'><tr style='background-color: #4D8732;'><td colspan='4' style='color: white; border: 1px solid #818181;' align='left'><b>Purchase Order Detail</b></td></tr><tr><td><b>PO No</b></td><td colspan='3' align='left'>" + lblpurchaseorder.Text + "</td></tr><tr><td><b>Bill Format</b></td><td>" + lblBillFormat.Text + "</td><td><b>Supplier</b></td><td align='left'>" + lblsupplier.Text + "</td></tr><tr><td><b>Leased Type</b></td><td>" + lblleagetype.Text + "</td><td><b>Delivery Location</b></td><td>" + lbllocation.Text + "</td></tr><tr><td><b>Currency</b></td><td>" + lblCurrency.Text + "</td><td></td></tr></table></td></tr><tr><td><table style='border: 1px solid #818181; width: 100%; font-family: Arial, Helvetica, sans-serif; font-size: small; font-weight: normal;' cellpadding='0' cellspacing='0'><tr style='background-color: #4D8732;'><td colspan='5' style='color: white; border: 1px solid #818181;'><b>Item Detail</b></td></tr><tr><td style='border: 1px solid #818181; width: 40%;'><b>Item Name / Item Code</b></td><td style='border: 1px solid #818181; width: 10%;'><b>UOM</b></td><td style='border: 1px solid #818181; width: 10%;'><b>Qty</b></td><td style='border: 1px solid #818181; width: 10%;'><b>Rate</b></td><td style='border: 1px solid #818181; width: 15%;'><b>Amount Payable</b></td></tr>" + Body.Text + "</table></td></tr><tr><td><table cellpadding='0' cellspacing='0'><tr><td style='border: 1px solid #818181; width: 40%;'></td><td style='border: 1px solid #818181; width: 10%;'><b>Item Total</b></td><td style='border: 1px solid #818181; width: 10%;' align='right'>" + Convert.ToDecimal(hidtotalQty.Value).ToString("N0") + "</td><td style='border: 1px solid #818181; width: 10%;'><b>Taxable Amount</b></td><td align='right' style='border: 1px solid #818181; width: 15%;'>" + Convert.ToDecimal(hidtaxtotal.Value) + "</td></tr></table></td></tr><tr><td><b>Thanks & Regards</b></td></tr><tr><td><a href='http://103.13.97.96/demo/index.aspx' target='_blank'>Click here for login</a></td></tr></table>";
                System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient();
                smtp.Host = DtMail.Rows[1]["MailHost"].ToString().Trim();
                smtp.Port = 587;
                smtp.UseDefaultCredentials = false;
                smtp.Credentials = new System.Net.NetworkCredential(DtMail.Rows[1]["MailUserID"].ToString().Trim(), DtMail.Rows[1]["MailPassword"].ToString().Trim());
                smtp.EnableSsl = true;
                smtp.Send(mail);
            }
        }
        catch (Exception ex)
        {
        }
    }
    #endregion
    //for the Gridview Binding value
    #region
    protected void grdDisplay_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            string po_id = grdDisplay.DataKeys[e.Row.RowIndex].Value.ToString();
            string sql_select = "select Status from ACC_POMAIN where POID=" + Convert.ToInt32(po_id);
            DataTable DTStatus = DU.getdata(sql_select);
            if (DTStatus.Rows.Count > 0)
            {
                if (DTStatus.Rows[0]["Status"].ToString() == "3")
                {
                    e.Row.Cells[8].FindControl("lnkbtnEdit").Visible = false;
                    e.Row.Cells[8].FindControl("imgapproved").Visible = false;
                }
                if (DTStatus.Rows[0]["Status"].ToString() == "4")
                {
                    e.Row.Cells[8].FindControl("lnkbtnEdit").Visible = false;
                    e.Row.Cells[8].FindControl("imgapproved").Visible = false;
                }
                if (DTStatus.Rows[0]["Status"].ToString() == "5")
                {
                    e.Row.Cells[8].FindControl("lnkbtnEdit").Visible = true;
                    e.Row.Cells[8].FindControl("imgapproved").Visible = false;
                    e.Row.Cells[8].FindControl("imgReject").Visible = false;
                    e.Row.Cells[8].FindControl("imgRevision").Visible = false;
                }
                if (DTStatus.Rows[0]["Status"].ToString() == "6")
                {
                    e.Row.Cells[8].FindControl("lnkbtnEdit").Visible = false;
                    e.Row.Cells[8].FindControl("imgapproved").Visible = false;
                }
                if (DTStatus.Rows[0]["Status"].ToString() == "7")
                {
                    e.Row.Cells[8].FindControl("lnkbtnEdit").Visible = false;
                    e.Row.Cells[8].FindControl("imgapproved").Visible = false;
                }
                if (DTStatus.Rows[0]["Status"].ToString() == "8")
                {
                    e.Row.Cells[8].FindControl("lnkbtnEdit").Visible = false;
                    e.Row.Cells[8].FindControl("imgapproved").Visible = true;
                    e.Row.Cells[8].FindControl("imgReject").Visible = false;
                    e.Row.Cells[8].FindControl("imgRevision").Visible = false;
                }
                if (DTStatus.Rows[0]["Status"].ToString() == "9")
                {
                    e.Row.Cells[8].FindControl("lnkbtnEdit").Visible = false;
                    e.Row.Cells[8].FindControl("imgapproved").Visible = false;
                    e.Row.Cells[8].FindControl("imgReject").Visible = false;
                    e.Row.Cells[8].FindControl("imgRevision").Visible = true;
                }
                if (DTStatus.Rows[0]["Status"].ToString() == "10")
                {
                    e.Row.Cells[8].FindControl("lnkbtnEdit").Visible = false;
                    e.Row.Cells[8].FindControl("imgapproved").Visible = false;
                    e.Row.Cells[8].FindControl("imgReject").Visible = true;
                    e.Row.Cells[8].FindControl("imgRevision").Visible = false;
                }
            }
            GridView GrdPOChild = (GridView)e.Row.FindControl("gvPORemarksChild");
            string SqlChildRemarks = "select ACC_POREMARKS.POSTAGE,ACC_POREMARKS.REMARKS,ACC_POREMARKS.REVISIONREMARK,ACC_POREMARKS.REVISIONORDER,ACC_POREMARKS.REJECTREMARK,ACC_POMAIN.PODATE from ACC_POREMARKS inner join ACC_POMAIN on ACC_POMAIN.POID=ACC_POREMARKS.POID where ACC_POMAIN.POID=" + Convert.ToInt32(po_id);
            DataTable DTPurchaseRemarks = DU.getdata(SqlChildRemarks);
            DataTable DTChildPO = new DataTable();
            DTChildPO.Columns.Add("POSTAGE", typeof(string));
            DTChildPO.Columns.Add("REMARKS", typeof(string));
            DTChildPO.Columns.Add("REVISIONORDER", typeof(string));
            DTChildPO.Columns.Add("CDATE", typeof(string));
            DTChildPO.Columns.Add("CTIME", typeof(string));
            if (DTPurchaseRemarks.Rows.Count > 0)
            {
                for (int i = 0; i < DTPurchaseRemarks.Rows.Count; i++)
                {
                    DataRow DR = DTChildPO.NewRow();
                    if (DTPurchaseRemarks.Rows[i]["POSTAGE"].ToString() == "2")
                    {
                        DR["POSTAGE"] = "Manager";
                    }
                    if (DTPurchaseRemarks.Rows[i]["POSTAGE"].ToString() == "3")
                    {
                        DR["POSTAGE"] = "Finance";
                    }
                    if (DTPurchaseRemarks.Rows[i]["POSTAGE"].ToString() == "4")
                    {
                        DR["POSTAGE"] = "Admin";
                    }
                    //DR["POSTAGE"] = DTPurchaseRemarks.Rows[i]["POSTAGE"].ToString();
                    DR["REMARKS"] = DTPurchaseRemarks.Rows[i]["REMARKS"].ToString();
                    DR["REVISIONORDER"] = DTPurchaseRemarks.Rows[i]["REVISIONORDER"].ToString();
                    DR["CDATE"] = Convert.ToDateTime(DTPurchaseRemarks.Rows[i]["PODATE"].ToString()).ToString("dd-MMM-yyyy");
                    //DR["CTIME"] = Convert.ToDateTime(DTPurchaseRemarks.Rows[i]["CDATE"].ToString()).ToString("hh:mm:ss tt");
                    DTChildPO.Rows.Add(DR);
                }
            }
            GrdPOChild.DataSource = DTChildPO;
            GrdPOChild.DataBind();
        }
    }
    protected void grdDisplay_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "Edit")
        {
            string key = (string)e.CommandArgument;
            //Response.Redirect("PurchaseOrderApproval.aspx?mode=edit&key=" + key);
            Response.Redirect("AdminPurchaseOrderApproval.aspx?mode=edit&key=" + key);
        }
    }
    protected void grdDisplay_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        grdDisplay.PageIndex = e.NewPageIndex;
        bindgrid();
    }
    protected void grdDisplay_RowCreated(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType != DataControlRowType.Pager)
        {
            if (e.Row.RowState == DataControlRowState.Alternate)
            {
                e.Row.Attributes.Add("onmouseover", "this.className='rowhover'");
                e.Row.Attributes.Add("onmouseout", "this.className='gridview_alternate'");
                //e.Row.Attributes.Add("onclick", "this.className='rowselected'");
            }
            else if (e.Row.RowState == DataControlRowState.Normal)
            {
                e.Row.Attributes.Add("onmouseover", "this.className='rowhover'");
                e.Row.Attributes.Add("onmouseout", "this.className='gridviewitem'");
                //e.Row.Attributes.Add("onclick", "this.className='rowselected'");
            }
        }

    }
    protected void DdlStatus_SelectedIndexChanged(object sender, EventArgs e)
    {

    }
    protected void grditem_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            TotalQty += Convert.ToInt32(DataBinder.Eval(e.Row.DataItem, "ITEMQTY"));
            TotalValue += Convert.ToDouble(DataBinder.Eval(e.Row.DataItem, "TotalAmount"));
        }
        if (e.Row.RowType == DataControlRowType.Footer)
        {
            Label lblTotalQty = (Label)e.Row.FindControl("lbltotalQty");
            lblTotalQty.Text = TotalQty.ToString();
            Label lblTotalValue = (Label)e.Row.FindControl("lbltotalAmount");
            lblTotalValue.Text = Convert.ToDouble(TotalValue).ToString("N2");
        }
    }
    #endregion
    //For the Save of the Data of the Page
    #region
    protected void BtnClose_Click(object sender, EventArgs e)
    {
        Response.Redirect("AdminPurchaseOrderApproval.aspx");
    }
    protected void btnReject_Click(object sender, EventArgs e)//For Reject
    {
        MailBody();
        string IP = IpAddress();
        SqlParameter[] parm ={                                 
                              new SqlParameter("@adminip",IP),
                              new SqlParameter("@POID",Request.QueryString["key"].ToString()),
                              new SqlParameter("@Status","10"),//10 For Reject from Admin.
                              //new SqlParameter("@Remarks",txtRejectRemarks.Text),
                              new SqlParameter("@adminid",Session["username"].ToString()),
                              new SqlParameter("@stages","4")                                  
                           };
        int intse = DU.executeprocedure("USP_UpdateByAdmin_ACC_POMAIN", parm);
        POREJECTREMARKS();
        SendEMail("is Rejected");// Mail For Rejection Of the PO.
        lblMsg.Attributes.Remove("class");
        lblMsg.Attributes.Add("class", "true");
        lblMsg.Text = "Purchase order is Rejected ...";
        Response.Redirect("AdminPurchaseOrderApproval.aspx");
    }
    protected void BtnUpdate_Click(object sender, EventArgs e)//for Approved
    {
        MailBody();
        string IP = IpAddress();
        SqlParameter[] parm ={                                 
                                  new SqlParameter("@adminip",IP),
                                  new SqlParameter("@POID",Request.QueryString["key"].ToString()),
                                  new SqlParameter("@Status","8"),//For Approved from Admin.
                                  new SqlParameter("@adminid",Session["username"].ToString()),
                                  new SqlParameter("@stages","4")                                   
                               };
        int intse = DU.executeprocedure("USP_UpdateByAdmin_ACC_POMAIN", parm);
        //POAPPROVEREMARKS();
        SendEMail("has been Approved");
        lblMsg.Attributes.Remove("class");
        lblMsg.Attributes.Add("class", "true");
        lblMsg.Text = "Purchase order Approved by Admin sucessfully...";
        Response.Redirect("AdminPurchaseOrderApproval.aspx");
    }
    protected void btnRevision_Click(object sender, EventArgs e) //For Revision
    {
        //for Revision No Increment.
        MailBody();
        int RevisionNO = 0;
        string IP = IpAddress();
        string sqlrevision = "select Revision_no,status from ACC_POMAIN where POID=" + Request.QueryString["key"].ToString();
        DataTable Dtrevision = DU.getdata(sqlrevision);
        if (Dtrevision.Rows.Count > 0)
        {
            if (Dtrevision.Rows[0]["status"].ToString() == "8")//8 for Admin Approved.
            {
                RevisionNO = Convert.ToInt32(Dtrevision.Rows[0]["Revision_no"].ToString());
            }
            else
            {
                RevisionNO = 0;
            }
        }
        SqlParameter[] parm ={                                 
                                  new SqlParameter("@adminip",IP),
                                  new SqlParameter("@POID",Request.QueryString["key"].ToString()),
                                  new SqlParameter("@Status","9"),//For Revision From Admin.
                                  new SqlParameter("@adminid",Session["username"].ToString()),
                                  new SqlParameter("@stages","4"), 
                                  new SqlParameter("@Revision_remarks",txtRevisionRemarks.Text),
                                  new SqlParameter("@Revision_No",RevisionNO)
                                 };
        int intse = DU.executeprocedure("USP_UpdateByAdmin_Revised", parm);
        POREVISIONREMARKS();//For Revision.
        SendEMail("Sent for Revision");// Mail For Revision Of the PO.
        lblMsg.Attributes.Remove("class");
        lblMsg.Attributes.Add("class", "true");
        lblMsg.Text = "Purchase Order Send For Revision ...";
        Response.Redirect("AdminPurchaseOrderApproval.aspx");
    }
    protected void POREJECTREMARKS()
    {
        try
        {
            SqlParameter[] ParamRem = {
                                          new SqlParameter("@POID",Request.QueryString["key"].ToString()),
                                          new SqlParameter("@POSTAGE","4"),
                                          new SqlParameter("@REMARKS","ReJect Remarks is:- "+txtRejectRemarks.Text),
                                          new SqlParameter("@CNAME",Session["username"].ToString())                                          
                                      };
            int insertRemarks = DU.executeprocedure("USP_ACC_INSERTPOREJECTREMARKS", ParamRem);
            if (insertRemarks > 0)
            {
                lblMsg.Text = "Purchase Order Updated Successfully";
            }
        }
        catch (Exception Ex)
        {
        }
    }
    protected void POREVISIONREMARKS()
    {
        try
        {
            int RevisionNO = 0;
            string sqlrevision = "select Revision_no,status from ACC_POMAIN where POID=" + Request.QueryString["key"].ToString();
            DataTable Dtrevision = DU.getdata(sqlrevision);
            if (Dtrevision.Rows.Count > 0)
            {
                if (Dtrevision.Rows[0]["status"].ToString() == "8")//8 for Admin Approved.
                {
                    RevisionNO = Convert.ToInt32(Dtrevision.Rows[0]["Revision_no"].ToString());
                }
                else
                {
                    RevisionNO = 0;
                }
            }
            SqlParameter[] ParamRem = {
                                          new SqlParameter("@POID",Request.QueryString["key"].ToString()),
                                          new SqlParameter("@POSTAGE","4"),
                                          new SqlParameter("@REMARKS","Revision Remarks is:- "+txtRevisionRemarks.Text),
                                          new SqlParameter("@CNAME",Session["username"].ToString()),
                                          new SqlParameter("@REVISIONORDER",RevisionNO)
                                      };
            int insertRemarks = DU.executeprocedure("USP_ACC_INSERTPOREVISIONREMARKS", ParamRem);
            if (insertRemarks > 0)
            {
                lblMsg.Text = "Purchase Order Updated Successfully";
            }
        }
        catch (Exception Ex)
        {
        }
    }
    #endregion   
}